package shuiyuqing.activities;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.xkh.xkh.R;

import java.io.UnsupportedEncodingException;
import java.sql.Time;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.xkh.xkh.MyApplication;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import gis.activities.MapShow;
import managers.UIHandler;
import managers.VolleySingleton;
import shuiyuqing.network.beans.IrrBRStadia;
import shuiyuqing.network.http.DownloadInfo;
import shuiyuqing.network.http.GetHistoryWaterDam;
import shuiyuqing.views.adapters.HistoryWaterAdapter;
import utils.TimeUtil;

/**
 * 水情历史查询
 * Created by 凯 on 2015/11/11.
 */
public class WaterHistoryActivity extends UIHandler.BaseActivity implements GetHistoryWaterDam.Delegate {

    // 测站
    IrrBRStadia stadia;

    // 日期选择器
    DatePickerDialog dialog;

    // 选择日期界面
    View v_datePicker;

    // 选择的日期
    int year;
    int month;
    int day;

    // 状态
    int status = 1;

    String str_data;

    // 返回按钮
    Button btn_back;

    // 选择中的时间
    TextView tv_time;

    // 水情历史
    ListView lv_dayhistory;

    // 根据条件筛选
    Button tv_choose;

    // 历史
    HistoryWaterAdapter historyWaterAdapter;

    PullToRefreshListView pullToRefreshListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waterhistory);

        initview();
        initdata();
    }

    View.OnClickListener itemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == v_datePicker) {
                dialog.show();
            } else if (v == btn_back) {
                finish();
            }
        }
    };


    // 弹出查询条件
    private void popCondition() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.window_history_condition, null);
        final EditText et_time_begin = (EditText) layout.findViewById(R.id.id_time_begin);
        final EditText et_time_end = (EditText) layout.findViewById(R.id.id_time_end);


        String time = TimeUtil.currentTimeSP3();
        et_time_begin.setText(TimeUtil.beforeDay3(7));
        et_time_end.setText(time);


        final AlertDialog dialog = new AlertDialog.Builder(this).setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String beginTime = et_time_begin.getText().toString();
                String endTime = et_time_end.getText().toString();

                if (!checkd(beginTime, endTime)) {
                    return;
                }


                fetchDataByCondition(beginTime, endTime);
                dialog.dismiss();
            }
        });
    }

    // 检查时间格式是否正确
    private boolean checkd(String beginTime, String endTime) {
        if (!beginTime.matches("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]")) {
            Toast.makeText(MyApplication.share(), "起始时间格式不正确", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!endTime.matches("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]")) {
            Toast.makeText(MyApplication.share(), "终止时间格式不正确", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 年月日是否正确
        Calendar before = TimeUtil.getCalendarByStr2(beginTime);
        Calendar end = TimeUtil.getCalendarByStr2(endTime);

        if (before == null || end == null) {
            Toast.makeText(MyApplication.share(), "格式不正确", Toast.LENGTH_SHORT).show();
            return false;
        }

        long interday = TimeUtil.dayInter(before, end);
        if (interday > 0 && interday < 10) {
            return true;
        } else {
            Toast.makeText(MyApplication.share(), "时间相差不能超过10天", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    // 根据日期查询
    private void fetchDataByCondition(final String beginTime, final String endTime) {
        status = 2;
        showDialog();

        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/guanqu/GetHistWaterGateDamByTime";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        closeDialog();
                        GetHistoryWaterDam.Download download = JSON.parseObject(response, GetHistoryWaterDam.Download.class);
                        if (download.getStatus() == DownloadInfo.SUCCESS) {
                            historyWaterAdapter.getDam().setDownload(download);
                            historyWaterAdapter.notifyDataSetChanged();

                        } else if (download.getStatus() == DownloadInfo.FAILED) {

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                closeDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("stadia", stadia.getStadiaCode());
                map.put("before", beginTime);
                map.put("end", endTime);
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    // 初始化界面
    private void initview() {

        // 根据条件筛选
        tv_choose = (Button) findViewById(R.id.choose);
        tv_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popCondition();
            }
        });

        // 返回按钮
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(itemClick);

        v_datePicker = findViewById(R.id.id_v_pickTime);
        v_datePicker.setOnClickListener(itemClick);

        // 显示选择时间
        tv_time = (TextView) findViewById(R.id.id_tv_date);

        // 日期选择器
        Calendar calendar = Calendar.getInstance();
        dialog = new DatePickerDialog(WaterHistoryActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                WaterHistoryActivity.this.setDate(year, monthOfYear + 1, dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));


        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.id_refreshlistview);
        lv_dayhistory = pullToRefreshListView.getRefreshableView();
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.id_refreshlistview);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (status == 2) {
                    UIHandler.uiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            pullToRefreshListView.onRefreshComplete();
                        }
                    });

                }
                if (status == 1) {
                    getmore();
                }
            }
        });

        // 列表设置数据源
        historyWaterAdapter = new HistoryWaterAdapter();
        historyWaterAdapter.setDam(new GetHistoryWaterDam(null, null));
        lv_dayhistory.setAdapter(historyWaterAdapter);


    }

    // 获取更多的加载信息
    private void getmore() {
        if (tv_time.getText().toString().isEmpty()) {
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        if (stadia == null || historyWaterAdapter.getDam() == null || historyWaterAdapter.getDam().getDownload() == null || historyWaterAdapter.getDam().getDownload().getDams().isEmpty()) {
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        GetHistoryWaterDam.Upload upload2 = new GetHistoryWaterDam.Upload();
        upload2.setStadiaCode(stadia.getStadiaCode());
        upload2.setFirst(1);
        upload2.setStamp(historyWaterAdapter.getDam().getDownload().getDams().
                get(historyWaterAdapter.getDam().getDownload().getDams().size() - 1).
                getMeaTime().getTimeInMillis());
        upload2.setDate(str_data);
        new GetHistoryWaterDam(this, upload2).get();


    }

    // 初始化数据
    private void initdata() {
        stadia = (IrrBRStadia) getIntent().getSerializableExtra("stadia");
    }

    // 设置时间
    public void setDate(int year, int monthOfYear, int dayOfMonth) {
        status = 1;
        String month_strOfYear = "";
        if (monthOfYear <= 9) {
            month_strOfYear = "0" + monthOfYear;
        } else {
            month_strOfYear = "" + monthOfYear;
        }


        String day_strOfMonth = "";
        if (dayOfMonth <= 9) {
            day_strOfMonth = "0" + dayOfMonth;
        } else {
            day_strOfMonth = "" + dayOfMonth;
        }

        String str_date = year + "-" + month_strOfYear + "-" + day_strOfMonth;
        this.str_data = str_date;
        tv_time.setText(str_date);

        // 所选时间
        if (TimeUtil.compareTime(str_date) < 0) {

        } else if (TimeUtil.compareTime(str_date) == 0) {
            // 今天

        } else {
            // 明天
            if (historyWaterAdapter != null)
                historyWaterAdapter.getDam().getDownload().getDams().clear();
            historyWaterAdapter.notifyDataSetChanged();
            return;
        }


        historyWaterAdapter.getDam().getDownload().getDams().clear();
        historyWaterAdapter.notifyDataSetChanged();

        this.year = year;
        this.month = monthOfYear;
        this.day = dayOfMonth;

        // 重新获取此时间段内的所有数据
        if (stadia != null) {
            GetHistoryWaterDam.Upload upload2 = new GetHistoryWaterDam.Upload();
            upload2.setStadiaCode(stadia.getStadiaCode());
            upload2.setDate(str_date);
            upload2.setFirst(0);
            new GetHistoryWaterDam(this, upload2).get();


        }
    }

    // 下载完成后
    @Override
    public void onResponse(String response, GetHistoryWaterDam dam) {
        pullToRefreshListView.onRefreshComplete();
        if (dam.getDownload().getStatus() == DownloadInfo.SUCCESS) {
            if (dam.getDownload().getDams().size() == 0) {
                Toast.makeText(MyApplication.share(), "没有更多数据了", Toast.LENGTH_SHORT).show();
            }

            // 设置显示数据
            historyWaterAdapter.getDam().getDownload().getDams().addAll(dam.getDownload().getDams());
            historyWaterAdapter.notifyDataSetChanged();

        } else if (dam.getDownload().getStatus() == DownloadInfo.FAILED) {

        }
    }

    @Override
    public void onErrorResponse(VolleyError error, GetHistoryWaterDam dam) {
        pullToRefreshListView.onRefreshComplete();
    }
}
